// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/expression/row_constructor.h>
#include <pollux/expression/vector_function.h>

namespace kumo::pollux::exec {
    TypePtr RowConstructorCallToSpecialForm::resolveType(
        const std::vector<TypePtr> &argTypes) {
        auto numInput = argTypes.size();
        std::vector<std::string> names(numInput);
        std::vector<TypePtr> types(numInput);
        for (auto i = 0; i < numInput; i++) {
            types[i] = argTypes[i];
            names[i] = fmt::format("c{}", i + 1);
        }
        return ROW(std::move(names), std::move(types));
    }

    ExprPtr RowConstructorCallToSpecialForm::constructSpecialForm(
        const TypePtr &type,
        std::vector<ExprPtr> &&compiledChildren,
        bool trackCpuUsage,
        const core::QueryConfig &config) {
        auto [function, metadata] = vectorFunctionFactories().withRLock(
            [&config](auto &functionMap) -> std::pair<
        std::shared_ptr<VectorFunction>,
        VectorFunctionMetadata> {
                auto functionIterator = functionMap.find(kRowConstructor);
                if (functionIterator != functionMap.end()) {
                    return {
                        functionIterator->second.factory(kRowConstructor, {}, config),
                        functionIterator->second.metadata
                    };
                } else {
                    POLLUX_FAIL("Function {} is not registered.", kRowConstructor);
                }
            });

        return std::make_shared<Expr>(
            type,
            std::move(compiledChildren),
            function,
            metadata,
            kRowConstructor,
            trackCpuUsage);
    }
} // namespace kumo::pollux::exec
